<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title" style="text-align: center;">
                <div
                    style="margin-left: 0px; height: 40px;width: 350px; text-align: center;line-height: 40px;float: left;font-weight: bold;">
                    {{ data.po_name }}&nbsp;{{ data.po_code }}</div>
                <div
                    style="margin: 0 auto; height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handAudit">审核</el-button>
                    <!-- <el-button plain @click="handleDeactivate">停用</el-button> -->
                </div>
            </div>
            <hr>


            <!-- 商品信息表格 -->
            <table style="width: 100%; border-collapse: collapse;border: none;">
                <tbody>
                    <!-- 货品类型行 -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">供应商昵称</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.po_Vendor_Name }}
                        </td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">联系人</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.contacts_Name }}</td>
                        <td style="padding: 10px 0px; color: #666;">联系电话</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.contacts_Phone }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">订单签订日期</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.po_Starttime }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">订单交付日期</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.po_Endtime }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">采购负责人</td>
                        <td style="padding: 10px 0px 10px 10px; min-width: 50px;">{{ userValue(data.po_Rep_Id) }}</td>
                    </tr>

                    <!-- 供应商行 -->
                    <!-- <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 10px 15px; color: #666;">供应商</td>
                        <td style="padding: 10px;">供应商一</td>
                        <td style="padding: 10px 15px; color: #666;">客户名称</td>
                        <td style="padding: 10px;" colspan="3">客户十</td>
                    </tr> -->

                    <!-- 保质期行 -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">负责人部门</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ deptValue(data.po_depd_id)}}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">订单状态</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ ddValue(data.po_State) }}</td>
                    </tr>

                    <tr>
                        <td style="padding: 10px 0px; color: #666;">创建人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.create_By }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">创建时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ data.create_Time}}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">修改人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.update_By||'暂无修改' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">修改时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ data.update_Time||'暂无修改'}}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">审核人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.po_Audit_By||'暂未审核' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">审核时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ data.po_Audit_Time||'暂无审核'}}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="section">
            <el-menu mode="horizontal" :default-active="activeTab" @select="handleTabChange" :ellipsis="false">
                <el-menu-item index="details">采购记录</el-menu-item>
                <el-menu-item index="outbound">入库记录</el-menu-item>
                <el-menu-item index="stores">退货记录</el-menu-item>
            </el-menu>
            <!-- 主内容区 -->
            <component :is="currentComponent" :code="selectedCode" @code-selected="handleCodeSelected"/>
        </div>

        <!-- </div> -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="customer_handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, watch, toRaw, markRaw, inject,computed  } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute,useRouter } from 'vue-router';
import { Delete, TurnOff } from '@element-plus/icons-vue'
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import details from './Poinfo_details.vue'
import outbound from './Poinfo_pb.vue'
import stores from './Poinfo_pu.vue'
// import { useStore } from 'vuex'


export default {
    setup() {
        const store = useStore()
        const datamax = store.state.PO_UpdeteArray
        const data = reactive({
            po_name: '',//采购单名称
            po_code: '',//采购单编号
            po_Vendor_Name:'',//供应商昵称
            contacts_Name:'',//联系人
            contacts_Phone:'',//联系电话
            po_Starttime:'',//订单签订日期
            po_Endtime:'',//订单交付日期
            po_Rep_Id:'',//采购负责人
            po_depd_id:'',//负责人部门
            po_State:'',//订单状态
            create_By:'',//创建人
            create_Time:'',//创建时间
            update_By:'',//修改人
            update_Time:'',//修改时间
            po_Audit_By:'',//审核人
            po_Audit_Time:'',//审核时间
        })

        const activeTab = ref('details') // 默认显示采购记录
        const selectedCode = ref()     // 传递给子组件的 code
        const componentMap = {
            details,    // 对应 index="details" 和 Poinfo_details.vue
            outbound,   // 对应 index="outbound" 和 Poinfo_pb.vue
            stores      // 对应 index="store" 和 Poinfo_pu.vue
        
        }
        const currentComponent = computed(() => componentMap[activeTab.value])

        // 切换标签页
        const handleTabChange = (tab) => {
            activeTab.value = tab
        }

        // 接收子组件传递的 code
        const handleCodeSelected = () => {
            console.log("这是什么，我也不知道")
            // selectedCode.value = data.po_code
        }
        //-----------------------------------以上是子组件-----------------------------------

        const Router = useRouter();
        const route = useRoute();
        const router = useRouter();
        // const datamax = JSON.parse(String(route.query.rowData));

        const activeMenu = ref('')//当前选中的菜单
        
        const ClassifyOptios = ref([])//供应商分类
        const deptOptions = ref([])//部门
        const userOptions = ref([])//用户
        const termOptions = ref([])//期限
        const centerDialogVisible = ref(false);//审核拟态框
        const auditStatus = ref('1');//审核状态
        const auditOpinion = ref('');//审核意见
        onMounted(() => {
            // getClassify()
            getUser()
            getDept()
            // getterm()
            info()
        })
        //查询供应商分类
        function getClassify() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_datamax", {
                params: {
                    dict_type: "Customer_classify"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                ClassifyOptios.value = result.data
                // console.log(result.data)
            }).catch((err) => {
                console.info(err) 
            });
        }
        //将数据中的vendor_classify转换为对应的dict_label
        function ClassifyValue(row){
            // console.log(row)
            if (!row) return "无";
            const parentDept = ClassifyOptios.value.find((d) => d.dict_value == row);
            // console.log(parentDept)
            return parentDept ? parentDept.dict_label : "无";
        }
        //查询用户
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }
        //查询部门
        function getDept() {
            axios.get("http://localhost:5181/api/Dept/DeptOpt", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }
        //将数据中的vendor_depd_id转换为对应的dept_name
        function deptValue(row) {
            if (!row) return "无";
            const parentDept = deptOptions.value.find((d) => d.dept_id == row)
            return parentDept ? parentDept.dept_name : "无"
        }
        //将数据中的vendor_rep_id转换为对应的user_name
        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOptions.value.find((d) => d.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }
        //查询期限
        function getterm(){
            axios.get("http://localhost:5181/api/Dict/Get_Dict_datamax", {
                params: {
                    dict_type: "settlement_period"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                termOptions.value = result.data
            }).catch((err) => {
                console.info(err) 
            });
        }
        //将数据中的vendor_term转换为对应的dict_label
        function termValue(row){
            if (!row) return "无";
            const parentDept = termOptions.value.find((d) => d.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        //编辑
        function handleEdit() {
            // 编辑逻辑
            // console.log(datamax)
            if(datamax.po_Audit !='0'){
                ElMessage.error("已审核的订单不可编辑");
            }else{
                store.commit('PO_UpdeteArray', datamax)
                Router.push({
                path: '/main/Pinv/PoUpdate',
                // query:{
                //     rowData: JSON.stringify(datamax)
                // }
            })
            }
        }
        //点击审核按钮
        function handAudit(){
            if (datamax.po_Audit==0) {
                centerDialogVisible.value = true
            }else{
                ElMessage.warning('该订单已被审核，不可再次审核！')
            }
        }
        //关闭审核框
        function close(){
            centerDialogVisible.value = false
            auditStatus.value = '1'
            auditOpinion.value = ''
        }
        function updateAudit(){
            // console.log("进来了")
            axios.put("http://localhost:5181/api/Po/PutPoUpdateAudit", {
                po_Id: datamax.po_Id,
                po_Audit_By: localStorage.getItem('userLName'),
                po_Audit_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                po_Audit_Remark: auditOpinion.value,
                po_Audit: auditStatus.value
            }, {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    if (auditStatus.value == '1') {
                        ElMessage.success('审核通过')
                    } else if (auditStatus.value == '2') {
                        ElMessage.warning('审核已被驳回！')
                    }
                    close()
                    customer_handleClose()
                }
            }).catch((err) => {
                console.info(err)
            });
        }
        //删除
        function handleDelete(){
            ElMessageBox.confirm(
                '此操作将删除该产品信息，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
            .then(() => {
                if(datamax.po_Audit!='0'){
                    ElMessage.error("删除失败,已审核的订单不可删除");
                }else{
                    return axios.put('http://localhost:5181/api/Po/PutPoDelete', {
                    po_Id: datamax.po_Id,
                    del_flag: "1"
                }, {
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                });
                }
            })
            .then((result) => {
                if (result.data>0) {
                    ElMessage.success("删除成功");
                    Router.push({
                        path: '/main/Pinv/vendor',
                    });
                } else {
                    console.log(datamax.po_Id)
                    ElMessage.error("删除失败");
                }
                customer_handleClose();
            })
            .catch((error) => {
                console.error('删除失败:', error);
                // if (error !== 'cancel') {  // 只有当错误不是用户取消时才显示错误
                //     console.error('删除失败:', error);
                //     ElMessage.error("删除失败");
                // }
            });
        }
        //关闭
        const closeTab = inject('closeTab'); // 注入关闭方法
        function customer_handleClose(){
            Router.push({
                    path: '/main/Pinv/Po',
                });
                const targetPath = "/main/Pinv/Po";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "采购订单",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }
        //格式化 ISO 时间字符串为 YYYY-MM-DD HH:MM:SS
        function datetime(isoTime){
            if (!isoTime) return '';
            const date = new Date(isoTime);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
        }

        //订单状态
        function ddValue(state){
            const statusMap = {
                0 : '未入库' ,
                 2 : '部分入库' ,
                 3 : '已完成' ,
                 8 : '未入库' ,
                 7 : '部分退货' ,
                 6 : '超额退货' ,
                 9 : '全部退货' ,
                
      }
      return statusMap[state] || '未知状态'
        }

        //将数据中的数据赋值给data
        function info(){
            // console.log(datamax)
            // data.vendor_id = datamax.vendor_id
            data.po_code = datamax.po_Code
            data.po_name = datamax.po_Name
            data.po_Vendor_Name = datamax.po_Vendor_Name
            data.contacts_Name = datamax.contacts_Name
            data.contacts_Phone = datamax.contacts_Phone
            data.po_Starttime = datamax.po_Starttime
            data.po_Endtime = datamax.po_Endtime
            data.po_Rep_Id = datamax.po_Rep_Id
            data.po_depd_id = datamax.po_depd_id
            data.po_State = datamax.po_State
            data.create_By = datamax.create_By
            data.create_Time = datetime(datamax.create_Time)
            data.update_By = datamax.update_By
            data.update_Time = datetime(datamax.update_Time)
            data.po_Audit_By = datamax.po_Audit_By
            data.po_Audit_Time = datetime(datamax.po_Audit_Time)
            selectedCode.value = datamax.po_Code
            // console.log("当前code"+selectedCode.value)
        }
        return {
            datamax,
            data,
            ClassifyOptios,
            deptOptions,
            userOptions,
            termOptions,
            activeMenu,
            centerDialogVisible,
            auditStatus,
            auditOpinion,
            currentComponent,
            selectedCode,
            handleCodeSelected,
            handleTabChange,
            termValue,
            userValue,
            deptValue,
            ClassifyValue,
            handleEdit,
            handleDelete,
            customer_handleClose,
            datetime,
            handAudit,
            close,
            updateAudit,
            ddValue


        }
    }
}
</script>

<style scoped>
.goods-add-form{
    margin-top: -40px;
}

.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.section1 {
    padding: 20px;
    height: 390px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 1205px;
    height: 40px;
}

.carousel-container {
    width: 100%;
    max-width: 230px;
    margin: 0 auto;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    overflow: hidden;
}

.customer_info_value {
    /* margin-left: 260px; */
    transform: translateX(260px) translateY(-230px);
    /* position: relative;
    top: -230px;
    left: 260px; */
    width: 945px;
    height: 330px;
    background-color: aqua;
}
</style>